package com.appspot.battlerafts.servlets.game;

import com.appspot.battlerafts.classes.Game;
import com.appspot.battlerafts.jsons.GameDataJSON;
import com.appspot.battlerafts.utils.PMF;
import com.google.gson.Gson;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.appspot.battlerafts.utils.Util.returnError;

/**
 * Created with IntelliJ IDEA.
 * User: Tonis
 * Date: 03.05.12
 * Time: 23:26
 * To change this template use File | Settings | File Templates.
 */
public class PlayerLeftGame extends HttpServlet {
    private static final Logger log = Logger.getLogger(PlayerLeftGame.class.getName());
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Gson gson = new Gson();
        String rawInput = request.getParameter("data");
        GameDataJSON leftGameJSON = gson.fromJson(rawInput, GameDataJSON.class);
        log.info("THIS PLAYER LEFT: " + leftGameJSON.playerUID +"; GAME WITH ID: " + leftGameJSON.gameID);
        log.setLevel(Level.INFO);

        PersistenceManager pm = PMF.get().getPersistenceManager();
        Game game;
        try {
            game = (Game) pm.getObjectById(Game.class, leftGameJSON.gameID);
            findAndRemoveRegisteredPlayer(leftGameJSON, game);
            pm.makePersistent(game);
        }catch (JDOObjectNotFoundException e) {
            log.info(e.toString());
            returnError(response, "Game with id " + leftGameJSON.gameID + " was not found in our database!");
            return;
        } finally {
            pm.close();
        }
    }

    private void findAndRemoveRegisteredPlayer(GameDataJSON leftGameJSON, Game game) {
        ArrayList<Long> registered = game.getRegisteredPlayers();
        for (int i = 0; i < registered.size(); i++){
            if (registered.get(i).equals(leftGameJSON.playerUID)){
                registered.remove(i);
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
